/**
 * Created by think on 2015/1/11.
 *
 * 连接 postgresQL
 */

var config = require("../../config");
var pg = require("pg");
var pgTransact = require('pg-transact');
var Q = require('q');
var colors = require('colors');

function _connect(connectStr, callback) {
  var defer = Q.defer();
  pg.connect(connectStr, function(err, client, done) {
    if (err) {
      defer.reject(err);
    } else {
      defer.resolve({client:client, done:done});
    }
  });
  return defer.promise.nodeify(callback);
}

function execQuery(sql, params, options, callback) {
  if (typeof options == 'function') {
    callback = options;
    options = {};
  }
  if (!options) {
    options = {};
  }
  if (!sql) {
    var err = new Error("sql is null");
    var defer3 = Q.defer();
    return defer3.reject(err).nodeify(callback);
  }

  //是否打印SQL语句
  if (config.postgres.debug) {
    console.log(sql.green);
    console.log(params);
  }
  var connectStr = config.postgres.url;
  return _connect(connectStr)
    .then(function(result) {
      var client = result.client;
      var done = result.done;

//      function transaction (client) {
//        var defer2 = Q.defer();
//        client.query(sql, params, function(err, result) {
//          if (err) {
//            defer2.reject(err);
//          } else {
//            defer2.resolve(result);
//          }
//        })
//        return defer2.promise;
//      }

//      if (options.transaction == true) {
//        //支持事务模式
//        return pgTransact(client, transaction, done)
//      } else {
        //不支持事务模式
        var defer = Q.defer();
        client.query(sql, params, function(err, result) {
          done();
          if (err) {
            defer.reject(err);
          } else {
            defer.resolve(result);
          }
        })
        return defer.promise;
//      }
    })
    .nodeify(callback);
}

module.exports = execQuery;
module.exports.execQuery = execQuery;